package app.serialport;

import app.serialport.ByteUtil;

public class DelimiterDecoder implements Decoder {
	
	private byte[] delimiterBytes;
	
	public DelimiterDecoder(String delimiter) {
		this.delimiterBytes = ByteUtil.hexString2Bytes(delimiter);
	}
	
	public DelimiterDecoder(byte[] delimiterBytes) {
		this.delimiterBytes = delimiterBytes;
	}

	@Override
	public byte[] decode(byte[] data) {
		if(data.length < delimiterBytes.length) {
			return null;
		}
		
		int delimiterLength = delimiterBytes.length;
		int dataLength = data.length;
		for (int i = 0; i < delimiterBytes.length; i++) {
			if(delimiterBytes[i] != data[dataLength-delimiterLength+i]) {
				return null;
			}
		}
		
		return data;
		
//		int start = 0;
//		int end = 0;
//		for (int i=0;i<data.length-1;i++) {
////			boolean isMatchStart = match(data[i], "8A") && match(data[i+1], "8A");
////			if(isMatchStart) {
////				start = i;
////				continue;
////			}
//			
//			boolean isMatchEnd = match(data[i], "8B") && match(data[i+1], "8B");
//			if(isMatchEnd) {
//				end = i+2;
//				
//				byte[] single = ArrayUtils.subarray(data, start, end);
//				result.add(single);
//			}
//		}
//		
//		if(end != 0) {
//			currentIndex = data.length - end;
//			if(currentIndex != 0) {
//				System.arraycopy(data, end, buffer, 0, currentIndex);
//			}
//		}
//		
//		return result;
	}
}
